package com.example.demo.utils;

import java.io.File;

import com.example.demo.config.WebParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class HtmlToPdf {

	/** The log. */
	private static Logger log = LoggerFactory.getLogger(HtmlToPdf.class.getName());

	@Autowired
	private WebParameter webParameter;

	public String getCommand() {
		String system = System.getProperty("os.name");
		if(system.contains("Windows")) {
			return webParameter.getTopdftool();
		}else if(system.contains("Linux")) {
			return "wkhtmltopdf";
		}else if(system.contains("Mac")) {
			return "wkhtmltopdf";
		}
		return "";
	}

	/**
	 * html转pdf
	 * 
	 * @param srcPath
	 *            html路径，可以是硬盘上的路径，也可以是网络路径
	 * @param destPath
	 *            pdf保存路径
	 * @return 转换成功返回true
	 */
	public boolean convert(String srcPath, String destPath) {
		srcPath = srcPath.replace(",pdf","");
		log.info("HTML2PDF ，参数---html路径：{} , 保存路径 ：{}", new Object[] { srcPath, destPath });

		File file = new File(destPath);
		File parent = file.getParentFile();
		// 如果pdf保存路径不存在，则创建路径
		if (!parent.exists()) {
			parent.mkdirs();
		}

		StringBuilder cmd = new StringBuilder();
		cmd.append(getCommand());
		cmd.append(" ");
		//cmd.append("--page-size A2");// 参数
		cmd.append(" ");
		cmd.append(srcPath);
		cmd.append(" ");
		cmd.append(destPath);

		boolean result = true;
		Process proc = null;
		HtmlToPdfInter error = null;
		HtmlToPdfInter output = null;
		try {
			proc = Runtime.getRuntime().exec(cmd.toString());
			log.info("HTML2PDF  output.start() cmd:{}" ,cmd.toString());
			proc.waitFor();
			log.info("HTML2PDF成功，参数---html路径：{},  保存路径 ：{}", new Object[] { srcPath, destPath });
		} catch (Exception e) {
			log.error("HTML2PDF失败，srcPath地址：{},错误信息：{}", new Object[] { srcPath, e.getMessage() });
			result = false;
		}finally {
			if (proc != null){
				proc.destroy();
			}
		}
		return result;
	}

}